/*
 * Copyright 2017 JessYan
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package me.jessyan.lifecyclemodel.demo.slice;

import me.jessyan.lifecyclemodel.demo.MyApplication;
import me.jessyan.lifecyclemodel.demo.ResourceTable;
import me.jessyan.lifecyclemodel.LifecycleModelProviders;
import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.ability.fraction.FractionManager;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.agp.window.dialog.ToastDialog;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import rx.functions.Action1;

/**
 * ================================================
 * AFraction 通过 {@link UserLifecycleModel#addAction(Action1)} 注册需要与其他组件通讯的事件以及逻辑
 * ================================================
 */
public class AFraction extends Fraction {
    private static int id;
    private final HiLogLabel lable = new HiLogLabel(HiLog.LOG_APP, 0x00201, "Fraction");

    //    静态类，外部调用的方法，与外部通信
    public static AFraction createAAbilitySlice(FractionManager fractionManager, int i) {
        AFraction fraction = new AFraction();
        fractionManager.startFractionScheduler().add(i, fraction).submit();
        id = i;
        return fraction;
    }

    /**
     * 获取AFraction的xml
     **/
    @Override
    protected Component onComponentAttached(LayoutScatter scatter, ComponentContainer container, Intent intent) {
        Component component;
        component = scatter.parse(ResourceTable.Layout_fraction_a, null, false);
        return component;
    }

    /**
     * AFraction创建时调用
     **/


    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
//        接收
        final UserLifecycleModel lifecycleModel = LifecycleModelProviders.of(getFractionAbility(), id).get(UserLifecycleModel.class.getName());

        lifecycleModel.addAction(new Action1<String>() {
            @Override
            public void call(String s) {
                // Update the UI.
                MyApplication application = (MyApplication) getFractionAbility().getAbilityPackage();
                new ToastDialog(application.getApplicationContext()).setText("A接收B的传参--s:" + s).show();
                HiLog.info(lable, "A接收B的传参--s:" + s);
            }
        });
    }
}
